<script setup lang="ts">
import { reactive, ref, watch } from "vue"
import { Search, Refresh, CirclePlus, RefreshRight, Plus } from "@element-plus/icons-vue"
import { EditUserInfo, QueryUserInfoTableParams } from "@/api/user/types/info"
import { usePagination } from "@/hooks/usePagination"
import { deleteUserInfo, getUserInfoTableData, appendUserInfo, updateUserInfo } from "@/api/user/info"
import { ElMessage, ElMessageBox, FormInstance, FormRules, UploadProps, UploadRequestOptions } from "element-plus"
import { cloneDeep } from "lodash-es"
import { uploadFile } from "@/api/file"

const loading = ref(false)
const { paginationData, handleCurrentChange } = usePagination({ layout: "total, prev, pager, next, jumper" })

// #region 增
const DEFAULT_FORM_DATA: EditUserInfo = {
  id: "",
  email: "",
  gender: null,
  phone: "",
  userAvatar: "",
  userAccount: "",
  userName: "",
  userProfile: "",
  userRole: null,
  userPassword: ""
}

const avatarUploadRef = ref()
const dialogVisiable = ref(false)
const formRef = ref<FormInstance | null>()
const formData = ref(cloneDeep(DEFAULT_FORM_DATA))
const formRules: FormRules = {
  userAvatar: [{ type: "string", message: "请上传头像", trigger: "change" }],
  userAccount: [{ type: "string", required: true, message: "请填写账号名称", trigger: "blur" }],
  userName: [{ type: "string", required: true, message: "请填写用户名", trigger: "blur" }],
  userProfile: [
    { type: "string", message: "请填写用户简介", trigger: "blur" },
    { min: 4, trigger: "blur" }
  ],
  userRole: [
    { type: "string", required: true, message: "请选择用户类型", trigger: "change" },
    {
      trigger: "change",
      validator: (rule, val, cb) => {
        if (val !== "admin" && val !== "user" && val !== "company") {
          cb("用户类型未知，请重新选择")
        } else {
          cb()
        }
      }
    }
  ],
  phone: [
    { type: "string", required: true, message: "请输入手机号", trigger: "blur" },
    {
      trigger: "blur",
      validator: (rule, val, cb) => {
        const reg = /^1[3-9]\d{9}$/
        if (Number.isInteger(Number(val)) && Number(val) > 0 && reg.test(val)) {
          cb()
        } else {
          cb("您输入的手机号格式不正确，必须是11位的国内手机号")
        }
      }
    }
  ],
  gender: [
    { type: "number", required: true, message: "请选择性别", trigger: "change" },
    {
      trigger: "change",
      validator: (rule, val, cb) => {
        console.log(val)
        if (val !== 0 && val !== 1) {
          cb("您的性别未知，请重新选择")
        } else {
          cb()
        }
      }
    }
  ],
  email: [{ type: "string", required: true, message: "请填写邮箱", trigger: "blur" }]
}

function handleCreateOrUpdate() {
  formRef.value?.validate((valid: boolean, fields) => {
    if (!valid) return console.error("表单检验不通过", fields)
    loading.value = true
    const api = formData.value.id === "" ? appendUserInfo : updateUserInfo
    api(formData.value)
      .then(() => {
        ElMessage.success("操作成功")
        dialogVisiable.value = false
        getTableData()
      })
      .finally(() => {
        loading.value = false
      })
  })
}
function resetForm() {
  formRef.value?.clearValidate()
  formData.value = cloneDeep(DEFAULT_FORM_DATA)
}

const uploadAvatarFile = (opts: UploadRequestOptions) => {
  const { file } = opts
  const formData = new FormData()
  formData.append("file", file)
  formData.append("biz", "user_avatar")
  return uploadFile(formData)
}
const handleUploadAvatarSuccess: UploadProps["onSuccess"] = ({ data }) => {
  formData.value.userAvatar = data
}
//#endregion

// #region 删
function handleDelete(row: EditUserInfo) {
  ElMessageBox.confirm(`正在删除用户:${row.userName}，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() =>
    deleteUserInfo(Number(row.id)).then(() => {
      ElMessage.success("删除成功")
      getTableData()
    })
  )
}
//#endregion

// #region 改
function handleUpdate(row: EditUserInfo) {
  dialogVisiable.value = true
  formData.value = cloneDeep(row)
}
//#endregion

// #region 查
const genderOptions = [
  {
    value: 0,
    label: "女"
  },
  {
    value: 1,
    label: "男"
  }
]
const userTypeOptions = [
  {
    value: "admin",
    label: "管理员"
  },
  {
    value: "company",
    label: "企业"
  },
  {
    value: "user",
    label: "普通用户"
  }
]
const tableData = ref()
const searchFormRef = ref<FormInstance | null>()
const searchData = reactive<QueryUserInfoTableParams>({
  id: undefined,
  userName: "",
  phone: "",
  email: "",
  gender: undefined,
  userRole: undefined,
  current: 1,
  pageSize: 10,
  sortField: "id",
  sortOrder: "desc"
})
function getTableData() {
  loading.value = true
  getUserInfoTableData({
    email: searchData.email,
    gender: searchData.gender,
    id: searchData.id,
    phone: searchData.phone,
    userName: searchData.userName,
    userRole: searchData.userRole,
    current: 1,
    pageSize: 10,
    sortField: "id",
    sortOrder: "desc"
  })
    .then(({ data }) => {
      paginationData.total = data.total
      tableData.value = data.records
    })
    .catch(() => {
      tableData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}
function handleSearch() {
  paginationData.current === 1 ? getTableData() : (paginationData.current = 1)
}
function resetSearch() {
  searchFormRef.value?.resetFields()
  handleSearch()
}
//#endregion

watch([() => paginationData.current, () => paginationData.pageSize], getTableData, { immediate: true })
</script>

<template>
  <div class="app-container">
    <el-card v-loading="loading" shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true">
        <el-form-item label="用户名">
          <el-input v-model="searchData.userName" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="searchData.phone" placeholder="请输入手机号" clearable />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="searchData.email" placeholder="请输入邮箱" clearable />
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="searchData.gender" clearable placeholder="请选择性别" style="width: 150px">
            <el-option v-for="opt in genderOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="用户类型">
          <el-select v-model="searchData.userRole" clearable placeholder="请选择用户类型" style="width: 150px">
            <el-option v-for="opt in userTypeOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <div>
          <el-button type="primary" :icon="CirclePlus" @click="dialogVisiable = true">新增用户</el-button>
        </div>
        <div>
          <el-tooltip content="刷新当前页">
            <el-button type="primary" :icon="RefreshRight" circle @click="getTableData" />
          </el-tooltip>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table :data="tableData">
          <el-table-column type="selection" align="center" width="50" />
          <el-table-column prop="userAccount" label="账号名称" align="center" />
          <el-table-column prop="userName" label="用户名" align="center" />
          <el-table-column prop="userRole" label="角色" align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.userRole === 'admin'" type="primary" effect="plain"> admin </el-tag>
              <el-tag v-else-if="scope.row.userRole === 'company'" type="success"> company </el-tag>
              <el-tag v-else type="info" effect="plain" disable-transitions>{{ scope.row.userRole }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="phone" label="手机号" align="center" />
          <el-table-column prop="email" label="邮箱" align="center" />
          <el-table-column prop="gender" label="性别" align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.gender === 0" type="danger">女</el-tag>
              <el-tag v-else type="success">男</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" align="center">
            <template #default="scope">
              <span>{{ scope.row.createTime.split("+")[0].split("T").join(" ") }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="updateTime" label="更新时间" align="center">
            <template #default="scope">
              <span>{{ scope.row.updateTime.split("+")[0].split("T").join(" ") }}</span>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="150" align="center">
            <template #default="scope">
              <el-button type="primary" bg text size="small" @click="handleUpdate(scope.row)">修改</el-button>
              <el-button type="danger" bg text size="small" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :current-page="paginationData.current"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <el-dialog
      v-model="dialogVisiable"
      :title="formData.id === '' ? '新增用户' : '修改用户'"
      @close="resetForm"
      width="30%"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="80px" label-position="left">
        <el-form-item prop="userAccount" label="账号名">
          <el-input v-model.trim="formData.userAccount" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="userName" label="用户名">
          <el-input v-model.trim="formData.userName" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="userAvatar" label="头像">
          <el-upload
            ref="avatarUploadRef"
            class="avatar-uploader"
            action=""
            accept=".jpg,.jpeg,.png,.gif"
            :show-file-list="true"
            :limit="1"
            :http-request="uploadAvatarFile"
            :on-success="handleUploadAvatarSuccess"
          >
            <template v-if="!formData.userAvatar">
              <el-icon><Plus /></el-icon>
            </template>
            <template v-else>
              <img :src="formData.userAvatar" width="80" height="80" />
            </template>

            <template #tip>
              <div class="avatar-file-">jpg/jpeg/png/gif 文件 少于 10M</div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item prop="phone" label="手机号码">
          <el-input v-model.trim="formData.phone" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="email" label="邮箱">
          <el-input v-model.trim="formData.email" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="gender" label="性别">
          <el-select v-model="formData.gender!" placeholder="请选择性别">
            <el-option
              v-for="gender in genderOptions"
              :key="gender.value"
              :label="gender.label"
              :value="gender.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="userRole" label="用户角色">
          <el-select v-model="formData.userRole!" placeholder="请选择角色">
            <el-option
              v-for="userType in userTypeOptions"
              :key="userType.value"
              :label="userType.label"
              :value="userType.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisiable = false">取消</el-button>
        <el-button type="primary" @click="handleCreateOrUpdate">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.search-wrapper {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 20px;
  }
}

.toolbar-wrapper {
  display: flex;
  flex-flow: row nowrap;
  margin-bottom: 20px;
  justify-content: space-between;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
</style>
